import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List
from dataclasses import dataclass
from pydantic import BaseModel
app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()


class Note(BaseModel):
    keyid: int
    note: str = None


@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            note: Note = await websocket.receive_text()
            await manager.broadcast(note)
    except WebSocketDisconnect:
        manager.disconnect(websocket)


@app.post("/broadcast")
async def broadcast(item: Note):
    print(item)
    await manager.broadcast(item.model_dump_json())


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8008,
        log_level="debug",
        reload=True,
    )